﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ionic.Zip;
using System.IO;

namespace TorchView.PakViewer.Zip
{
    public class ZipNode : BaseZipNode
    {
        private ZipEntry _entry;
        
        public ZipNode(ZipEntry entry)
        {
            _entry = entry;
            IsDirectory = false;

            Path = entry.FileName;
            int start = Path.LastIndexOf("/");
            if (start < 0)
                Name = @"";

            //Is directory
            else if (start == Path.Length - 1)
            {
                start = Path.LastIndexOf("/", Path.Length - 2);
                if (start < 0)
                    Name = Path.Substring(0, Path.Length - 1);
                else
                    Name = Path.Substring(start + 1, Path.Length - start - 2);
            }
            else
                Name = Path.Substring(start + 1);
        }

        public ZipNode(ZipEntry entry, string name)
        {
            _entry = entry;
            IsDirectory = false;

            Path = entry.FileName;
            Name = name;
        }

        public Stream OpenFile()
        {
            var stream = _entry.OpenReader();
            byte[] buffer = new byte[(int)stream.Length];
            stream.Read(buffer, 0, buffer.Length);
            return new MemoryStream(buffer);
        }
    }
}
